import {Category, useTags} from '../../hooks/useTags';
import React, {useState} from 'react';
import {Editor} from '../../components/Editor';
import {Center} from '../../components/Center';
import {SaveButton} from '../../components/Button';
import {CategorySelector} from '../../components/CategorySelector';
import {TagInfoWrapper} from 'components/TagInfoWrapper';
import {SettingLayout} from '../../components/SettingLayout';
import {useHistory} from 'react-router-dom';

const TagAdder: React.FC = () => {
  const {doesTagNameExist, addTag} = useTags();
  const [selectedCategory, setSelectedCategory] = useState<Category>('-');
  const [tagName, setTagName] = useState('');
  const history = useHistory();
  const onAdd = () => {
    if (tagName === '') return;
    if (doesTagNameExist(tagName)) {
      alert(`标签名「${tagName}」已存在，不可重复设置`)
      return;
    }
    addTag({name: tagName, category: selectedCategory});
    alert('新增成功');
    history.goBack()
  };

  return (
    <SettingLayout title="新增标签">
      <TagInfoWrapper>
        <Editor label="标签名" type="text" placeholder="在这里输入标签名"
                value={tagName} onChange={(e) => {setTagName(e.target.value);}}/>
      </TagInfoWrapper>
      <TagInfoWrapper>
        <CategorySelector value={selectedCategory} onClick={(s) => {setSelectedCategory(s);}}/>
      </TagInfoWrapper>

      <Center>
        <SaveButton onClick={onAdd}>确认新增</SaveButton>
      </Center>
    </SettingLayout>
  );
};

export {TagAdder};